package com.punai.customer.excelparse;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.punai.common.core.domain.BaseEntity;
import com.punai.common.core.domain.CommonConstants;
import com.punai.customer.domain.CusMechanicalChapter;
import com.punai.customer.domain.CusMechanicalItem;
import com.punai.customer.mapper.CusMechanicalChapterMapper;
import com.punai.customer.mapper.CusMechanicalItemMapper;

import java.util.*;

public class MechanicalExcelParseListener extends AnalysisEventListener<Map<Integer, String>> {

    private final CusMechanicalChapterMapper cusMechanicalChapterMapper;
    private final CusMechanicalItemMapper cusMechanicalItemMapper;
    private final Long companyId;
    private final Long userId;
    private final Long deptId;
    private final String byUser;
    int pageNum = 1;
    Integer batchNun = 2000;
    List<CusMechanicalChapter> chapters = new ArrayList<>();
    List<CusMechanicalItem> items = new ArrayList<>();
    // 对应chapterId 与 序号的关系
    Map<String,String> chapterIdNum = new HashMap<>();
    Map<String,String> chapterPidsMap = new HashMap<>();
    Map<String,Integer> orderNumMap = new HashMap<>();

    public MechanicalExcelParseListener(CusMechanicalChapterMapper cusMechanicalChapterMapper,
                                        CusMechanicalItemMapper cusMechanicalItemMapper,
                                        Long companyId, Long userId, Long deptId, String byUser) {
        this.cusMechanicalChapterMapper = cusMechanicalChapterMapper;
        this.cusMechanicalItemMapper = cusMechanicalItemMapper;
        this.companyId = companyId;
        this.userId = userId;
        this.deptId = deptId;
        this.byUser = byUser;
    }

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        if (pageNum == 1) {
            CusMechanicalChapter chapter = parseChapter(data);
            chapters.add(chapter);
        } else {
            CusMechanicalItem item = parseItem(data);
            items.add(item);
            if (items.size() >= batchNun) {
                saveItem();
            }
        }
    }


    private CusMechanicalItem parseItem(Map<Integer, String> data) {
        CusMechanicalItem item = new CusMechanicalItem();
        String rId = IdUtil.randomUUID();
        String pxh = data.get(0);
        String code = data.get(1);
        String name = data.get(2);
        String unit = data.get(3);
        String ggxh = data.get(4);
        item.setId(rId);
        String chapterId = chapterIdNum.get(pxh);
        item.setChapterId(StrUtil.emptyToDefault(chapterId,"0"));
        item.setCode(code);
        item.setItemName(name);
        item.setUnit(unit);
        item.setSpec(ggxh);
        item.setOrderNum(getOrderNum(chapterId));
        item.setCompanyId(companyId);
        item.setUserId(userId);
        item.setDeptId(deptId);
        setCreateContent(item);
        return item;
    }


    private CusMechanicalChapter parseChapter(Map<Integer, String> data) {
        CusMechanicalChapter chapter = new CusMechanicalChapter();
        String rId = IdUtil.randomUUID();
        chapter.setId(rId);
        String xh = data.get(0);
        String pxh = data.get(1);
        String code = data.get(2);
        String name = data.get(3);
        // 费用项使用
        chapterIdNum.put(xh,rId);
        String pid = StrUtil.equals(pxh, CommonConstants.DEF_PID) ? CommonConstants.DEF_PID : chapterIdNum.get(pxh);
        // pids
        chapter.setPid(pid);
        chapter.setPids(getPids(rId,pid));
        chapter.setChapterName(name);
        chapter.setCode(code);
        chapter.setOrderNum(getOrderNum(pid));
        chapter.setCompanyId(companyId);
        chapter.setUserId(userId);
        chapter.setDeptId(deptId);
        setCreateContent(chapter);
        return chapter;
    }

    private void setCreateContent(BaseEntity baseEntity) {
        Date now = new Date();
        baseEntity.setCreateBy(byUser);
        baseEntity.setUpdateBy(byUser);
        baseEntity.setCreateTime(now);
        baseEntity.setUpdateTime(now);
    }

    private String emptyToDhDefault(String str) {
        if (StrUtil.isEmpty(str)) {
            return "";
        }
        return "," + str;
    }

    private String getPids(String rId,String pid) {
        String pids = pid + emptyToDhDefault(chapterPidsMap.get(pid));
        chapterPidsMap.put(rId,pids);
        return pids;
    }


    private Integer getOrderNum(String pid) {
        Integer integer = orderNumMap.get(pid);
        if (integer == null) {
            orderNumMap.put(pid,1);
            return 1;
        }
        orderNumMap.put(pid,integer++);
        return integer;
    }

    private void saveChapter() {
        if (CollUtil.isNotEmpty(chapters)) {
            cusMechanicalChapterMapper.insertBatchSomeColumn(chapters);
            chapters = new ArrayList<>();
        }
    }

    private void saveItem() {
        if (CollUtil.isNotEmpty(items)) {
            cusMechanicalItemMapper.insertBatchSomeColumn(items);
            items = new ArrayList<>();
        }
    }

    private void clearTempData() {
        orderNumMap = new HashMap<>();
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (pageNum == 1) {
            // 章节不会太多
            saveChapter();
            clearTempData();
            pageNum ++;
        } else {
            saveItem();
        }
    }
}
